<template>
  <d2-container>
    <el-main>
   
      <el-form ref="report" :model="report" label-width="80px" label-position="left"
               :rules="formRules">
                <el-form-item style="display: inline-block;position: absolute;top:10px;left:-30px" v-if="id != undefined">
                制表日期
                <el-date-picker :disabled='true'
                        v-model="report.date"
                        type="date"
                        placeholder="选择日期时间"
                        style='width: 150px'
                        >
                </el-date-picker>
            </el-form-item>
             <el-form-item style="display: inline-block;position: relative;top:10px;float: right;z-index: 100" v-if="id != undefined">
               <el-button type='primary' @click='exportExcel'>导出表格</el-button>
            </el-form-item>
        <el-row style='margin-top: 30px'>
        <el-form-item label="年份" prop="year" style="display: inline-block;width: 200px;">
          <el-input placeholder="年份" v-model="report.year" :disabled="disabled" type='number' step=1 @change='yearChange'></el-input>
        </el-form-item>
        <!-- <el-form-item label="周/月报" prop="gender" style="display: inline-block;margin-left: 50px"> -->
         <!--  <el-radio-group v-model="report.type" :disabled="disabled">
            <el-radio :label="0">周报</el-radio>
            <el-radio :label="1">月报</el-radio>
          </el-radio-group> -->
        <!-- </el-form-item> -->
         <el-form-item label="月份" prop="month" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="月份" v-model="report.month" :disabled="disabled" type='number' step=1 @change='monthChange' max='12'></el-input>
        </el-form-item >
         <el-form-item label="周数" prop="week" style="display: inline-block;width: 200px;margin-left: 50px" v-if="report.type == 0">
          <!-- <el-input placeholder="周数" v-model="report.week" :disabled="disabled" type='number' step=1 ></el-input> -->
            <el-select 
            v-model="report.week"
            placeholder="周数"
            @change="weekChange"
          >
            <el-option
              v-for="item in weeks"
              :key="item.index"
              :label="item.value"
              :value="item.index"
            ></el-option>
          </el-select>
        </el-form-item>
        
      </el-row>
      <el-row>
        <el-form-item label="报告人员" prop="name" style="display: inline-block;width: 200px;">
          <el-input placeholder="年份" v-model="report.staff.name" :disabled="true"></el-input>
        </el-form-item>
      
       <el-form-item label="手机" prop="cellphone" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="手机" v-model="report.staff.cellphone" :disabled="disabled"></el-input>
        </el-form-item>
      
       <el-form-item label="校长" prop="principlename" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="校长" v-model="report.principle.name" :disabled="disabled"></el-input>
        </el-form-item>
      
       <el-form-item label="校长手机" prop="principleCellphone" style="display: inline-block;width: 200px;margin-left: 50px">
          <el-input placeholder="校长手机" v-model="report.principle.cellphone" :disabled="disabled"></el-input>
        </el-form-item>
      </el-row>

      </el-form>

      <el-table border style="width: 70%" :data='reportData' :span-method='cellMerge' :row-style="{height:'200px'}">
      <el-table-column  label="项类" width="200" prop='name'>
       
      </el-table-column>
      <el-table-column  label="内容" prop='content'>
        <template slot-scope='scope'>
          <textarea v-model='scope.row.content' style="width: 100%;height: 200px" :disabled='disabled'>
            <!-- {{scope.row}} -->
          </textarea>

        </template>
      </el-table-column>
      
    </el-table>

    </el-main>
    <el-footer style="text-align: center">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="edit" v-show="id != undefined">修改</el-button>
    </el-footer>
  </d2-container>
</template>

<script>
import request from "@/plugin/axios";
import {mapState} from "vuex"
import formatTime from '@/libs/util.formatTime'
import excel from '@/libs/util.excel'
export default {
  data() {
    return {
      report :{
        type : 0,
        year : new Date().getFullYear(),
        month : new Date().getMonth() + 1,
        week : 1,
        staff : {name:'',cellphone:''},
        principle : {name:'',cellphone:''},
        date : formatTime.formatDate(String(new Date())),
        id : undefined
      },
      content : [],
      weeks : [],
      editShow: false,
      disabled: false,
      id: undefined,
      schoolList: [],
      reportData:[{name:'常规管理工作汇报',content:'【教务一周工作汇报】'},
      {name:'校区运营状态',content:'【人数】\n\n小棋士人数：\n\n本月累计流失人数：\n\n新开班情况：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'校区运营状态',content:'【课耗】\n\n本周计划完成：    ，实际完成：    ，课耗完成率：    \n\n累计课时创收：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'校区运营状态',content:'【续报】\n\n本月应续报人数：    本周实际完成：    ，完成金额：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'校区运营状态',content:'【停课】\n\n本周停课学员数：  ,本周停课激活数：   ，累计停课人数：\n\n停课激活亮点：\n\n停课（原因与措施）:'},
      {name:'校区运营状态',content:'【收支】\n\n本周收入：\n\n其他支出：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'教务教研',content:'【上周教研内容及总结】'},
       {name:'下周工作计划',content:''}],
      formRules: {
        name: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        
         date: [
          {required: true, message: '请选择制表时间', trigger: 'blur'},
          
        ],
      
       
        
      },
    };
  },
  computed:{
    ...mapState('d2admin/user',['info'])
  },
  methods: {
    cellMerge({row,column,rowIndex,columnIndex}){
      let rowspan = 1
      let colspan = 1
      if ((rowIndex == 1) && (columnIndex == 0)){
        rowspan = 5
      }
      if ((rowIndex <= 5) && (rowIndex > 1)){
        if (columnIndex == 0){
          rowspan = 0
        }
      }
      return {
        rowspan : rowspan,
        colspan :colspan
      }
     

    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    edit() {
      this.disabled = false;
    },
   
    submit() {
      if (this.report.year < 2019){
        this.$alert('','请输入正确年份')
        return false
      }
      if (this.staff == null){
        this.$alert('','请先绑定员工再重新登录')
        return false
      }
      let data = {};
      data.staff = this.staff
      data.principle = this.report.principle.name
      data.cellphone = this.report.staff.cellphone
      data.principleCellphone = this.report.principle.cellphone
      data.content = this.reportData.map(function(e){return e.content})
      data.school = this.school
      data.type = this.report.type
      data.year = this.report.year
      data.month = this.report.month
      data.week = this.report.week
      let url = "/staff/addReport";
      if (this.id != undefined) {
        data.id = this.id;
        url = "/staff/updateReport";
      }
        
      request({
        url: url,
        method: "post",
        data
      }).then(res => {
        if (res.code == 200) {
          this.refresh = true
          this.report = {
             type : 0,
        year : new Date().getFullYear(),
        month : new Date().getMonth() + 1,
        week : 1,
        staff : {name:'',cellphone:''},
        principle : {name:'',cellphone:''},
        date : formatTime.formatDate(String(new Date())),
        id : undefined
          }

          this.reportData = [{name:'常规管理工作汇报',content:'【教务一周工作汇报】'},
      {name:'校区运营状态',content:'【人数】\n\n小棋士人数：\n\n本月累计流失人数：\n\n新开班情况：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'校区运营状态',content:'【课耗】\n\n本周计划完成：    ，实际完成：    ，课耗完成率：    \n\n累计课时创收：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'校区运营状态',content:'【续报】\n\n本月应续报人数：    本周实际完成：    ，完成金额：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'校区运营状态',content:'【停课】\n\n本周停课学员数：  ,本周停课激活数：   ，累计停课人数：\n\n停课激活亮点：\n\n停课（原因与措施）:'},
      {name:'校区运营状态',content:'【收支】\n\n本周收入：\n\n其他支出：\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
      {name:'教务教研',content:'【上周教研内容及总结】'},
       {name:'下周工作计划',content:''}]

          this.$router.push({path: "/report-list"})
          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });
        }
        // 返回数据
      });
    },
    getReportOne(id) {
      request({
        url: "/staff/getReportOne",
        method: "post",
        data: {id: id}
      }).then(res => {
        if (res.code == 200) {
          this.report.principle = {name:res.data.principle}
          this.report.principle.cellphone = res.data.principleCellphone
          this.report.staff = res.data.staff
          this.report.date = formatTime.formatDate(new Date(res.data.date))
          this.report.id = id
          this.report.month = res.data.month
          this.report.week = res.data.week
          this.report.year = res.data.year
          this.report.staff.cellphone = res.data.cellphone
          this.report.type = res.data.type
          for (var i =0 ;i < res.data.content.length ; i++){
            this.reportData[i].content = res.data.content[i]
          }
        }
      });
    },

        exportExcel(){
      let output = []
      let merge = []
      output.push(['制表日期',this.report.date])
      output.push(['年份',this.report.year,'月份',this.report.month,'周',this.report.week])
      output.push(['报告人员',this.report.staff.name,'手机',this.report.staff.cellphone,'校长',this.report.principle.name,'校长手机',this.report.principle.cellphone])
      output.push([''])
      output.push(['项目','内容','','','','','','','',''])
      merge.push({s:{r:4,c:1},e:{r:4,c:9}})

      output.push (['常规管理工作汇报',this.reportData[0].content])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      merge.push({s:{r:5,c:0},e:{r:9,c:0}})
      merge.push({s:{r:5,c:1},e:{r:9,c:11}})
      output.push (['校区运营状态',this.reportData[1].content])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['',this.reportData[2].content])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['',this.reportData[3].content])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['',this.reportData[4].content])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['',this.reportData[5].content])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      output.push (['','','','','','','','','','','',''])
      merge.push({s:{r:10,c:0},e:{r:19,c:0}})
      merge.push({s:{r:10,c:1},e:{r:14,c:11}})
      merge.push({s:{r:15,c:1},e:{r:19,c:11}})
      merge.push({s:{r:20,c:1},e:{r:24,c:11}})
      merge.push({s:{r:25,c:1},e:{r:29,c:11}})
      merge.push({s:{r:30,c:1},e:{r:34,c:11}})
      output.push (['教务教研',this.reportData[6].content])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      merge.push({s:{r:35,c:0},e:{r:39,c:0}})
      merge.push({s:{r:35,c:1},e:{r:39,c:11}})
      output.push (['下周工作计划',this.reportData[7].content])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      output.push (['','','','','','','','','',''])
      merge.push({s:{r:40,c:0},e:{r:44,c:0}})
      merge.push({s:{r:40,c:1},e:{r:44,c:11}})
     
     
      

      excel.exportRaw(output,this.report.year + '年' + this.report.month + '月' + this.report.week + '周' + this.info.school[0].name + '月报',merge)
    },

   getMondays(thisYear,thisMonth) {
      var d = new Date(thisYear,thisMonth - 1),
          month = d.getMonth(),
          mondays = [];

      d.setDate(1);
      // Get the first Monday in the month
      while (d.getDay() !== 1) {
          d.setDate(d.getDate() + 1);
      }
      // Get all the other Mondays in the month
      while (d.getMonth() === month) {
        let mon = new Date(d.getTime())
          mondays.push({date:formatTime.formatDate(mon),org : mon});
          d.setDate(d.getDate() + 7);
      }
      return mondays;

  },
    getWeeks(){
      let year = this.report.year 
      let month = this.report.month 
      this.weeks = []
      this.getMondays(year,month).forEach((e,index)=>{
        this.weeks.push({value:e.date,index:index + 1,org:e.org})
      })
      this.weeks = this.weeks.sort((a,b)=>{return a.index -b.index})

    },
    monthChange(){
      this.getWeeks(this.report.year,this.report.month )
      this.report.week = 1
      this.loadData()
    },
    yearChange(){
      this.getWeeks(this.report.year,this.report.month )
      this.report.week = 1
      this.loadData()

    },
    weekChange(){
      this.loadData()
    },
    loadData(){
      let data ={}
      data.week = this.report.week
      data.weekDate = this.weeks[this.report.week - 1].org
      data.month = this.report.month
      data.year = this.report.year
      data.school = this.school
       request({
        url: "/data/getWeekReportData",
        method: "post",
        data: data
      }).then(res => {
        if (res.code == 200){
          let newClass = res.data.newClasses.map(e=>{return e.name + '(' + e.studentAmount + '人)'})
          if (newClass.length > 0){
            newClass.join('\n')
          }
          else{
            newClass = '无'
          }
          this.reportData = [{name:'常规管理工作汇报',content:'【教务一周工作汇报】'},
        {name:'校区运营状态',content:'【人数】\n\n小棋士人数：' + res.data.studentAmount +
        '\n\n本月累计流失人数：' + res.data.missStudent + 
        '\n\n新开班情况：' + newClass
        +'\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
        {name:'校区运营状态',content:'【课耗】\n\n本周计划完成：' + res.data.planCourseAmount +    '  ' +
        '，实际完成：' + res.data.actualCourseAmount + '  ' +
        '，课耗完成率：' + res.data.coursePercentage +     '%  ' +
        '\n\n累计课时创收：' + parseFloat(res.data.courseTotal).toFixed(1) + '元' + 
        '\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
        {name:'校区运营状态',content:'【续报】\n\n本月应续报人数：' + res.data.supposedContinueNumber + '  ' +
        '本周实际完成：' + res.data.actualContinueNumber + '   ' + 
        ' 完成金额：' + parseFloat(res.data.completeTotal).toFixed(1) + '元' + '   ' +
        '\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
        {name:'校区运营状态',content:'【停课】\n\n本周停课学员数：' + res.data.periodStopStudentAmount +
        '  ，本周停课激活数：' + res.data.periodactivateStudentAmount +
        '  ，累计停课人数：' + res.data.stopStudentAmount + 
        '\n\n停课激活亮点：\n\n停课（原因与措施）:'},
        {name:'校区运营状态',content:'【收支】\n\n本周收入：' + parseFloat(res.data.periodTotal).toFixed(1) +
        '\n\n其他支出：' + parseFloat(res.data.periodExpense).toFixed(1)
        +'\n\n亮点（文字分析）：\n\n不足（原因与改观措施）：'},
        {name:'教务教研',content:'【上周教研内容及总结】'},
        {name:'下周工作计划',content:''}]
        
      }

    })
    }
  },

  beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.report = to.meta.report
                  v.reportData = to.meta.reportData
                  to.meta.report = undefined
                  to.meta.reportData = undefined
                })
            }
            else{
                next()
            }
            next()

        },
        beforeRouteLeave(to,from,next){
          if (this.$route.query.id == undefined) {
            from.meta.keep = true
            from.meta.report = this.report      
            from.meta.reportData = this.reportData
          }
          if (this.refresh){
            to.meta.refresh = 'a'
          }

          next()
        },


  created() {
    this.school = this.info.school[0]._id
    this.staff = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
            this.school = this.info.school[0]._id
            this.report.staff.name = this.staffname
            this.report.staff._id = this.staff
            this.report.year = new Date().getFullYear()
            this.report.month = new Date().getMonth() + 1
            this.getWeeks()

    if (this.$route.query.id) {
      this.disabled = true;
      this.id = this.$route.query.id
      this.getReportOne(this.id)
    } else {
      this.loadData()
    }

    
  }
};
</script>
